const gulp = require('gulp');
const babel = require('gulp-babel');
const less = require('gulp-less');
const autoprefixer = require('gulp-autoprefixer');
const cssnano = require('gulp-cssnano');
const through2 = require('through2');

const paths = {
    dest: {
        lib: 'lib',
        esm: 'esm',
        dist: 'dist',
    },
    pack: 'package.json',
    styles: 'src/Acomponents/**/*.less',
    scripts: ['src/Acomponents/**/*.{ts,tsx}', '!src/Acomponents/**/demo/*.{ts,tsx}']
}

function cssInjection(content) {
    return content
        .replace(/\/style\/?'/g, "/style/css'")
        .replace(/\/style\/?"/g, '/style/css"')
        .replace(/\.less/g, '.css');
}

/**
 * 编译脚本文件
 * @param {string} babelEnv babel环境变量
 * @param {string} destDir 目标目录
 */
function compileScripts(babelEnv, destDir) {
    const { scripts } = paths;
    process.env.BABEL_ENV = babelEnv;
    return gulp
        .src(scripts)
        .pipe(babel()) // 使用gulp-babel处理
        .pipe(
            through2
            .obj(function z(file, encoding, next) {
                this.push(file.clone());
                // 找到目标
                if (file.path.match(/(\/|\\)style(\/|\\)index\.js/)) {
                    const content = file.contents.toString(encoding);
                    file.contents = Buffer.from(cssInjection(content)); // 文件内容处理
                    file.path = file.path.replace(/index\.js/, 'css.js'); // 文件重命名
                    this.push(file); // 新增该文件Î
                    next();
                } else {
                    next();
                }
            }),
        )
        .pipe(gulp.dest(destDir));
}

function compileCJS() {
    const { dest, scripts } = paths;
    return gulp
        .src(scripts)
        .pipe(babel()) // 使用gulp-babel处理
        .pipe(gulp.dest(dest.lib));
}

/**
 * 编译esm
 */
function compileESM() {
    const { dest } = paths;
    return compileScripts('esm', dest.esm);
}

/**
 * 拷贝less文件
 */
function copyLess() {
    return gulp
        .src(paths.styles)
        .pipe(gulp.dest(paths.dest.lib))
        .pipe(gulp.dest(paths.dest.esm));
}

/**
 * 生成css文件
 */
function less2css() {
    return gulp
        .src(paths.styles)
        .pipe(less()) // 处理less文件
        .pipe(autoprefixer()) // 根据browserslistrc增加前缀
        .pipe(cssnano({ zindex: false, reduceIdents: false })) // 压缩
        .pipe(gulp.dest(paths.dest.lib))
        .pipe(gulp.dest(paths.dest.esm));
}

function packageJSON() {
    return gulp
        .src(paths.pack)
        .pipe(gulp.dest(paths.dest.lib))
        .pipe(gulp.dest(paths.dest.esm))
}

// 串行执行编译脚本任务（cjs,esm） 避免环境变量影响
const buildScripts = gulp.series(compileCJS, compileESM);

// 整体并行执行任务
const build = gulp.parallel(buildScripts, copyLess, less2css, packageJSON);

// // 并行任务 后续加入样式处理 可以并行处理
// const build = gulp.parallel(compileCJS);

exports.build = build;

exports.default = build;